"""
管理后台 - 反馈管理接口
"""
from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import Optional, List
from pydantic import BaseModel
from datetime import datetime

from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.core.permissions import require_permission, Permission
from app.models.user import User
from app.models.venue_feedback import VenueFeedback, FeedbackStatus
from app.models.venue import Venue
from app.schemas.common import ApiResponse
from loguru import logger

router = APIRouter(prefix="/feedback", tags=["管理后台-反馈"])


class FeedbackListResponse(BaseModel):
    """反馈列表响应"""
    list: List[dict]
    total: int
    page: int
    pageSize: int


class HandleFeedbackRequest(BaseModel):
    """处理反馈请求"""
    status: str  # resolved, ignored
    note: Optional[str] = None


@router.get("/list", response_model=ApiResponse[FeedbackListResponse])
@require_permission(Permission.FEEDBACK_VIEW_ALL, Permission.FEEDBACK_VIEW_CITY)
async def get_feedback_list(
    page: int = Query(1, ge=1),
    pageSize: int = Query(20, ge=1, le=100),
    status: Optional[str] = Query(None),
    feedbackType: Optional[str] = Query(None),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取反馈列表"""
    logger.info(f"📋 获取反馈列表: page={page}")
    
    user_role = getattr(current_user, 'role', 'user')
    
    # 基础查询
    query = db.query(VenueFeedback)
    
    # 城市管理员只能看到自己城市的反馈
    if user_role == 'city_manager':
        user_city = getattr(current_user, 'city_name', None) or getattr(current_user, 'city_id', None)
        if user_city:
            # 通过 venue 关联查询
            query = query.join(Venue, VenueFeedback.venue_id == Venue.id, isouter=True)
            query = query.filter(
                or_(
                    Venue.city_name == user_city,
                    Venue.city_id == user_city,
                    VenueFeedback.venue_id.is_(None)  # 新场地建议没有关联场地
                )
            )
    
    # 状态筛选
    if status:
        query = query.filter(VenueFeedback.status == status)
    
    # 类型筛选
    if feedbackType:
        query = query.filter(VenueFeedback.feedback_type == feedbackType)
    
    # 总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * pageSize
    feedbacks = query.order_by(VenueFeedback.created_at.desc()).offset(offset).limit(pageSize).all()
    
    # 转换为字典并关联信息
    feedback_list = []
    for feedback in feedbacks:
        feedback_dict = feedback.to_dict()
        
        # 获取用户信息
        user = db.query(User).filter(User.id == feedback.user_id).first()
        if user:
            feedback_dict['userName'] = user.nick_name
            feedback_dict['userPhone'] = user.phone
        
        # 获取场地信息
        if feedback.venue_id:
            venue = db.query(Venue).filter(Venue.id == feedback.venue_id).first()
            if venue:
                feedback_dict['venueName'] = venue.name
                feedback_dict['venueCity'] = venue.city_name
        
        # 获取处理人信息
        if feedback.handled_by:
            handler = db.query(User).filter(User.id == feedback.handled_by).first()
            if handler:
                feedback_dict['handlerName'] = handler.nick_name
        
        feedback_list.append(feedback_dict)
    
    logger.success(f"✅ 返回反馈列表: total={total}, count={len(feedback_list)}")
    
    return ApiResponse(data={
        "list": feedback_list,
        "total": total,
        "page": page,
        "pageSize": pageSize
    })


@router.get("/{feedback_id}", response_model=ApiResponse[dict])
@require_permission(Permission.FEEDBACK_VIEW_ALL, Permission.FEEDBACK_VIEW_CITY)
async def get_feedback_detail(
    feedback_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取反馈详情"""
    feedback = db.query(VenueFeedback).filter(VenueFeedback.id == feedback_id).first()
    if not feedback:
        raise HTTPException(404, "反馈不存在")
    
    feedback_dict = feedback.to_dict()
    
    # 获取用户信息
    user = db.query(User).filter(User.id == feedback.user_id).first()
    if user:
        feedback_dict['userName'] = user.nick_name
        feedback_dict['userPhone'] = user.phone
    
    # 获取场地信息
    if feedback.venue_id:
        venue = db.query(Venue).filter(Venue.id == feedback.venue_id).first()
        if venue:
            feedback_dict['venueName'] = venue.name
            feedback_dict['venueCity'] = venue.city_name
    
    return ApiResponse(data=feedback_dict)


@router.post("/{feedback_id}/handle", response_model=ApiResponse[str])
@require_permission(Permission.FEEDBACK_HANDLE)
async def handle_feedback(
    feedback_id: str,
    request: HandleFeedbackRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """处理反馈"""
    logger.info(f"✅ 处理反馈: {feedback_id}, status: {request.status}")
    
    feedback = db.query(VenueFeedback).filter(VenueFeedback.id == feedback_id).first()
    if not feedback:
        raise HTTPException(404, "反馈不存在")
    
    # 城市管理员权限检查
    user_role = getattr(current_user, 'role', 'user')
    if user_role == 'city_manager' and feedback.venue_id:
        venue = db.query(Venue).filter(Venue.id == feedback.venue_id).first()
        if venue:
            user_city = getattr(current_user, 'city_name', None) or getattr(current_user, 'city_id', None)
            if user_city and venue.city_name != user_city:
                raise HTTPException(403, "无权处理其他城市的反馈")
    
    if request.status == 'resolved':
        feedback.status = FeedbackStatus.RESOLVED
        message = "已标记为已解决"
    elif request.status == 'ignored':
        feedback.status = FeedbackStatus.IGNORED
        message = "已忽略"
    else:
        raise HTTPException(400, "无效的状态")
    
    feedback.handled_by = current_user.id
    feedback.handled_at = datetime.now()
    feedback.handler_note = request.note
    
    db.commit()
    
    logger.success(f"✅ 反馈处理成功: {feedback_id}")
    
    return ApiResponse(message=message)

